var events = require('events');
var util = require('util');
var timers = require('timers');

/**
 * 
 * Manages events and periodic tasks.
 * 
 * @class TaskManager
 * @author jmanero
 * 
 * @requires events
 * @requires util
 * @requires timers
 * 
 * @constructor
 * @param {Funciton}
 *            callback
 * 
 */
var TaskManager = function(callback) {
	events.EventEmitter.call(this);

	taskManager = this;
	this.callback = callback;

	/**
	 * List of peridic event emitters
	 */
	this.emitters = {};

	if (typeof (this.callback) == 'function')
		this.callback();
	return this;
};

util.inherits(TaskManager, events.EventEmitter);

/**
 * 
 * Add an event emitting interval timer
 * 
 * @param {String}
 *            Event Name
 * @param {Number}
 *            Event period
 * 
 */
TaskManager.prototype.addEmitter = function(name, period) {

	this.emitters[name] = timers.setInterval(function() {
		taskManager.emit(name);
	}, period);
};

/**
 * Stop specified periodic emitter
 * 
 * @param {String}
 *            name
 * 
 */
TaskManager.prototype.removeEmitter = function(name) {

	timers.clearInterval(this.emitters[name]);
	delete this.emitters[name];
};

module.exports = TaskManager;
